from selenium import webdriver
import time, xlrd
from selenium.webdriver.common.action_chains import ActionChains
import pyautogui, pyperclip


# from enter_main_menu import *


# 登陆网站
def zhtj_login(drivers):
    drivers.get('https://zhtj.youth.cn/zhtj/')
    user_id = '410527198004140036'
    user_pw = '227718Lk'
    drivers.find_element_by_id('loginId').send_keys(user_id)
    drivers.find_element_by_id('password').send_keys(user_pw)
    user_yzm = input('Please input your yanking:')
    drivers.find_element_by_id('yzm').send_keys(user_yzm)
    drivers.find_element_by_id('subBut').click()
    return drivers


# 选择功能侧菜单
def side_menu(drivers, enter_menu=None):
    side_menu_dict = {}
    time.sleep(2)
    selected_son_menu = print_menu(drivers.find_element_by_id('side-menu').find_elements_by_tag_name('li'))
    time.sleep(1)
    # 有问题需要解决，元素display属性是False，所以无法显示菜单选择项,利用get_attribute('textContent')可以解决
    print_menu(selected_son_menu.find_elements_by_tag_name('li'), False)
    return drivers


# 打印菜单并选择
def print_menu(menu, switch=True):
    # print(menu)
    menu_dict = {}
    for index, value in enumerate(menu):
        if switch:
            if value.text != '':
                menu_dict[index] = value.text
        else:
            menu_dict[index] = value.get_attribute('textContent')
    # print(menu_dict)
    for key, value in menu_dict.items():
        print('       %d:%s' % (key, value))
    selected_menu_num = input('输入进入菜单数字:')
    selected_son_menu = menu[int(selected_menu_num)]
    selected_son_menu.click()
    return selected_son_menu


# 选择班级
def select_class(drivers, selected_class=''):
    # selected_class='2018级1班团支部'
    for value in drivers.find_elements_by_xpath(
            '/html/body/div/div/div[2]/div[2]/div/div[2]/div[1]/div[1]/ul/li[2]/div/ul'):
        if value.get_attribute('textContent') == selected_class:
            time.sleep(2)
            value.click()
            break


# 通过文件添加个人信息
def get_info(drivers):
    # 打开个人信息文件
    wb = xlrd.open_workbook(r'/home/m/2021年推荐入团积极分子名单(1).xls')
    ws = wb.sheet_by_name('member_info')
    info_list = ['bh', 'class', 'name', 'sfzh', 'address', 'telephone']
    i = 1
    # 排除sheet标题，从第一条有用信息开始执行
    for rows in range(20, ws.nrows):
        i += 1
        # 添加个人信息列表，列表解析式
        mem_list = [ws.row(rows)[i].value for i in range(ws.ncols - 1)]
        # 通过字典解析式，创建个人信息字典
        info_dict = {info: mem for info, mem in zip(info_list, mem_list)}
        print(info_dict)
        append_info(drivers, info_dict)
        # time.sleep(2)
        # 结束开关
        # if i==21:
        #     break
        # break


# 添加信息
def append_info(drivers, info_dict):
    # 选择班级
    select_class(drivers, info_dict['class'])
    time.sleep(3)
    drivers.find_element_by_id('name').send_keys(info_dict['name'])
    time.sleep(1)
    drivers.find_element_by_id('identityCardNo').send_keys(info_dict['sfzh'])
    time.sleep(1)
    drivers.find_element_by_id('reidentityCardNo').send_keys(info_dict['sfzh'])
    time.sleep(1)
    # 民族
    drivers.find_element_by_id('nationalId').click()
    select_dropdown_menu(drivers, 0)
    # 职业
    time.sleep(1)
    drivers.find_element_by_id('jobType').click()
    select_dropdown_menu(drivers, 0)
    # 在读情况
    time.sleep(1)
    drivers.find_element_by_id('job').click()
    select_dropdown_menu(drivers, 4)
    # 学历
    time.sleep(1)
    drivers.find_element_by_id('degreeId').click()
    select_dropdown_menu(drivers, 6)
    # 政治面貌
    drivers.find_element_by_id('politicalId').click()
    select_dropdown_menu(drivers, 0)
    # 入团时间
    drivers.find_element_by_id('joinLeagueTime').send_keys('2021-10')
    time.sleep(1)
    # 团员编号
    drivers.find_element_by_id('userCode').send_keys(info_dict['bh'])
    time.sleep(1)
    # 是否团干
    drivers.find_element_by_id('isCadres').click()
    select_dropdown_menu(drivers, 1)
    # 手机号码
    drivers.find_element_by_id('mobile').send_keys(int(info_dict['telephone']))
    time.sleep(1)
    # 户籍地址
    drivers.find_element_by_id('address').send_keys(info_dict['address'])
    time.sleep(1)
    # 是否志愿者
    drivers.find_element_by_id('isJoinVolunteerTime').click()
    select_dropdown_menu(drivers, 1)
    # 年龄超过18周岁，需判断是否提交入党申请
    if drivers.find_element_by_id('isPartyRecord').is_displayed():
        drivers.find_element_by_id('isPartyRecord').click()
        select_dropdown_menu(drivers, 1)
        time.sleep(1)
    # 上传志愿书，终极方案
    drivers.find_element_by_id('upRecord').click()
    file_path = r'/home/m/pdf_file/' + info_dict['name'] + '.pdf'
    pyperclip.copy(file_path)
    time.sleep(1)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter', presses=2)
    time.sleep(3)
    # 通过JavaScript
    # file_path = r'/home/m/pdf_file/' + info_dict['name'] + '.pdf'
    # js = 'document.getElementById("choose-league").removeAttribute("readonly");'
    # drivers.execute_script(js)
    # drivers.find_element_by_id('choose-league').send_keys(file_path)
    # time.sleep(10)
    # print(drivers.find_element_by_id('choose-league').get_attribute('placeholder'))
    # 手动选择代码
    # while True:
    #     if drivers.find_element_by_id('choose-league').get_attribute('placeholder')!='　请选择':
    #         break
    # 提交
    drivers.find_element_by_class_name('el-button--danger').click()
    time.sleep(15)
    # js = 'window.onload'
    # drivers.execute_script(js)
    drivers.find_element_by_xpath('/html/body/div/div/div[2]/div[1]/div/div[2]/ul/li[6]/ul/li[1]').click()
    time.sleep(1)


# 处理下拉选项菜单
def select_dropdown_menu(drivers, index):
    time.sleep(1.5)
    # 遍历显示所有的ul标签
    for i in drivers.find_elements_by_class_name('el-scrollbar__view'):
        # 当前是否被选中
        if i.is_displayed():
            i.find_elements_by_tag_name('li')[index].click()
            # print(i.is_displayed(), i.get_attribute('outerHTML'))
            break
    time.sleep(2)


if __name__ == '__main__':
    # 驱动实例化及窗口最大化和默认延迟时间
    drivers = webdriver.Chrome()
    my_action = ActionChains(drivers)
    drivers.maximize_window()
    drivers.implicitly_wait(5)
    # 登录系统，及功能菜单选择
    zhtj_drv = zhtj_login(drivers)
    time.sleep(2)
    zhtj_drv = side_menu(zhtj_drv)
    time.sleep(3)
    # 进入班级
    # zhtj_drv=select_class(zhtj_drv)
    """ 添加新团员信息 """
    get_info(zhtj_drv)

"""is_display,is_enabled,innerHTML,outerHTML,textContent,text
is_displayed 是否显示，True的话text可以显示文本内容，False的话就需要textContent
outerHTML 输出当前元素下的标签内容
is_enabled 当前是否可用
也可以通过JavaScript即脚本来执行，selenium有执行JavaScript脚本的方法:drivers.execute_script()
"""
